using System.Collections.ObjectModel;
using System.ComponentModel;
using LuceneSearch.ContactApp.Entities;
using LuceneSearch.ContactApp.Searching;
using NHibernate;

namespace LuceneSearch.ContactApp
{
    public class SearchScreenModel : INotifyPropertyChanged
    {
        private readonly ISessionFactory sessionFactory;
        private readonly IndexedEntitySearcher<Contact> indexedEntitySearcher;

        public SearchScreenModel(ISessionFactory sessionFactory, IndexedEntitySearcher<Contact> indexedEntitySearcher)
        {
            this.sessionFactory = sessionFactory;
            this.indexedEntitySearcher = indexedEntitySearcher;
            ContactCritera = new Contact();
            SearchResults = new ObservableCollection<Contact>();
        }

        public Contact ContactCritera { get; private set; }
        public ObservableCollection<Contact> SearchResults { get; private set; }

        public void Search()
        {
            SearchResult<Contact> result;

            using(var session = sessionFactory.OpenSession())
            {
                result = indexedEntitySearcher.Search(session, ContactCritera);                
            }

            UpdateSearchResults(result);
        }

        private void UpdateSearchResults(SearchResult<Contact> result)
        {
            SearchResults.Clear();

            SearchTime = string.Format("Search time: {0} milliseconds", result.SearchTime.TotalMilliseconds);
            NumberOfRecordsFound = string.Format("Number of records found: {0}", result.NumberOfResultsFound);

            foreach (var contact in result.Results)
            {
                SearchResults.Add(contact);
            }
        }

        private string numberOfRecordsFound;
        public string NumberOfRecordsFound
        {
            get { return numberOfRecordsFound; }
            set { numberOfRecordsFound = value; OnPropertyChanged(new PropertyChangedEventArgs("NumberOfRecordsFound")); }
        }

        private string searchTime;
        public string SearchTime
        {
            get { return searchTime; }
            set { searchTime = value; OnPropertyChanged(new PropertyChangedEventArgs("SearchTime")); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(PropertyChangedEventArgs args)
        {
            if(PropertyChanged == null) return;

            PropertyChanged(this, args);
        }
    }
}